﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Gateway.Interfaces;
using PServiceBus.Gateway.Redis.DTO;
using PServiceBus.Gateway.Interfaces.DTO;

namespace PServiceBus.Gateway.Redis {
    public class RedisGatewayService : IGatewayService {
        #region IMessageService Members

        public IGatewayServer Server { get; set; }

        public void RegisterRequestResponse() {
            Server.Register<RedisESBRequest, RedisESBTopicInfo>(SelectTopic);
            Server.Register<RedisESBRequest, RedisSubscriberInfo>(SelectSubscriber);
            Server.Register<RedisESBRequest, RedisTopicInfos>(GetTopics);
        }

        #endregion

        private static RedisSubscriberInfo ToRedisSubscriber(SubscriberInfo subscriber) {
            var sub = new RedisSubscriberInfo();
            sub.Durable = subscriber.Durable;
            sub.ID = subscriber.ID;
            sub.IsValid = subscriber.IsValid;
            sub.Name = subscriber.Name;
            sub.Topics = subscriber.Topics;
            sub.Transports = subscriber.Transports;
            return sub;
        }

        private static RedisSubscriberInfo SelectSubscriber(RedisESBRequest request) {
            var subscriber = MessageServiceBase.GetMessageBus(request.UserContext, reThrowException: request.ReThrowException, headers: request.Headers)
                .SelectSubscriber(request.Input, request.Headers);
            return ToRedisSubscriber(subscriber);
        }

        private static RedisESBTopicInfo SelectTopic(RedisESBRequest request) {
            return RedisESBTopicInfo.New(MessageServiceBase.GetMessageBus(request.UserContext, reThrowException: request.ReThrowException, headers: request.Headers)
                    .SelectTopic(request.Input, request.Headers));
        }

        private static RedisTopicInfos GetTopics(RedisESBRequest request) {
            return RedisTopicInfos.New(MessageServiceBase.GetMessageBus(request.UserContext, reThrowException: request.ReThrowException, headers: request.Headers).GetTopics(request.Headers).ToArray());
        }
    }
}
